package com.tpshion.chat.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @Description: netty服务
 * @Author: tpshion
 * @Date: 2020/5/18 18:27
 * @Version: 1.0
 */
@Slf4j
@Component
public class NettyServe {

    //主线程组
    private EventLoopGroup parentGroup;

    //从线程组
    private EventLoopGroup childGroup;

    /**
     * 服务启动
     */
    @PostConstruct
    public void start() throws InterruptedException {
        parentGroup = new NioEventLoopGroup();
        childGroup = new NioEventLoopGroup();
        //netty服务启动器
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(parentGroup, childGroup)
                       .channel(NioServerSocketChannel.class)
                       .childHandler(new ChannelInitializer<SocketChannel>() {

                           @Override
                           protected void initChannel(SocketChannel socketChannel) throws Exception {
                               ChannelPipeline pipeline = socketChannel.pipeline();
                               pipeline.addLast(new HttpServerCodec());
                               pipeline.addLast(new ObjectEncoder());
                               pipeline.addLast(new ChunkedWriteHandler());
                               pipeline.addLast(new HttpObjectAggregator(1024 * 64));
                               pipeline.addLast(new LoginHandler());
                               pipeline.addLast(new WebSocketServerProtocolHandler("/wschat"));
                               pipeline.addLast(new IdleStateHandler(60,60,60));
                               pipeline.addLast(new TextServeHandler());
                           }
                       }).bind(8888).sync();
        log.info("==============Netty Serve Start In 8888 ===============");
    }

    /**
     * 服务停止
     */
    @PreDestroy
    public void stop(){
        if(parentGroup != null){
            parentGroup.shutdownGracefully();
        }
        if(childGroup != null){
            childGroup.shutdownGracefully();
        }
    }
}
